package com.zhonghan.recharge.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.zhonghan.common.wechat.api.MessageApi;
import com.zhonghan.common.wechat.api.UserApi;
import com.zhonghan.common.wechat.bean.message.response.TextMessage;
import com.zhonghan.common.wechat.bean.user.BaseUserInfo;
import com.zhonghan.recharge.dao.WechatAccountDao;
import com.zhonghan.recharge.dao.WechatReplyDao;
import com.zhonghan.recharge.dao.WechatUserDao;
import com.zhonghan.recharge.pojo.WechatAccount;
import com.zhonghan.recharge.pojo.WechatReply;
import com.zhonghan.recharge.pojo.WechatUser;
import com.zhonghan.recharge.service.MessageService;
import com.zhonghan.recharge.task.TaskList;


@Service
public class MessageServiceImpl implements MessageService{

	private Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	private WechatReplyDao wechatReplyDao;
	
	@Autowired
	private WechatAccountDao wechatAccountDao;
	
	@Autowired
	private WechatUserDao wechatUserDao;
	
	@Autowired
	private JmsTemplate jmsQueueTemplate;
	
	@Override
	public String replyMessage(Map<String, String> map) {
		String fromUserName = map.get("FromUserName");
		String toUserName = map.get("ToUserName");
		String createTime = map.get("CreateTime");
		String msgType = map.get("MsgType");
		String content = map.get("Content");
		
		TextMessage textMessage = new TextMessage();
		textMessage.setToUserName(fromUserName);
		textMessage.setFromUserName(toUserName);
		textMessage.setCreateTime(new Date().getTime());
		
		String openId = null;
		try {
			String message = null;
			//如果回复文本消息
			if(MessageApi.MESSAGE_TEXT.equals(msgType)){
				
				WechatReply keywordsReply = new WechatReply();
				keywordsReply.setKeywords(content);
				// 从数据库查询是否包含改关键词,如果包含就返回关键词的内容回去
				List<WechatReply> replyList = wechatReplyDao.selectWechatReplyByObj(keywordsReply);
				if(replyList != null && replyList.size()>0){
					keywordsReply = replyList.get(0);
					if(keywordsReply.getMsgType().equals(MessageApi.MESSAGE_TEXT)){
						textMessage.setMsgType(MessageApi.MESSAGE_TEXT);
						textMessage.setContent(keywordsReply.getContent());
						message = MessageApi.textMessageToXml(textMessage);
						logger.info("通过关键字回复微信用户信息");
					}
				}else{
					// 如果不是关键字,就查询自动回复信息内容并返回
					WechatReply autoReply = new WechatReply();
					autoReply.setContent(content);
					List<WechatReply> autoReplyList = wechatReplyDao.selectWechatReplyByObj(autoReply );
					if(autoReplyList != null && autoReplyList.size() > 0){
						autoReply = autoReplyList.get(0);
						textMessage.setMsgType(autoReply.getMsgType());
						textMessage.setContent(autoReply.getContent());
						if(autoReply.getMsgType().equals(MessageApi.MESSAGE_TEXT)){
							textMessage.setMsgType(MessageApi.MESSAGE_TEXT);
							message = MessageApi.textMessageToXml(textMessage);
						}
						logger.info("自动回复微信用户信息");
					}else{
						/** // 后期存入数据库
						textMessage.setMsgType(MessageApi.MESSAGE_TEXT);
						textMessage.setContent("您的这个问题我暂时回答不了,需要等我主人给我升级下系统才行 ^_^");
						message = MessageApi.textMessageToXml(textMessage);
						logger.info("自动回复微信用户信息");
						*/
					}
				}
				
			}else if(MessageApi.MESSAGE_EVNET.equals(msgType)){
				String eventType = map.get("Event");
				//关注公众号事件回复消息
				if(MessageApi.MESSAGE_SUBSCRIBE.equals(eventType)){
					List<WechatAccount> accountList = wechatAccountDao.selectWechatAccount();
					WechatAccount wechatAccount = null;
					if(accountList != null && accountList.size() > 0){
						wechatAccount = accountList.get(0);
						//Token token = TokenApi.getToken(wechatAccount.getAppid(), wechatAccount.getAppsecret());
						// 这里的access_token是临时获取的,以后需要放在缓存中
						//BaseUserInfo baseUserInfo = UserApi.getUserInfo(token.getAccess_token(), fromUserName, "zh_CN");
						BaseUserInfo baseUserInfo = UserApi.getUserInfo(TaskList.Wechat_Access_Token, fromUserName, "zh_CN");
						logger.info(baseUserInfo);
						
						openId = baseUserInfo.getOpenId();
						String name;
						if(baseUserInfo.getNickname() != null){
							name = baseUserInfo.getNickname();
						}else{
							name = fromUserName;
						}
						
						// 先通过openId去数据库查,再保存用户数据到数据库
						WechatUser value = new WechatUser();
						value.setOpenId(baseUserInfo.getOpenId());
						
						try {
							List<WechatUser> wechatUserList = wechatUserDao.selectWechatUserByObj(value);
							
							value.setSubscribe(baseUserInfo.getSubscribe());
							value.setSubscribeTime(Long.parseLong(baseUserInfo.getSubscribeTime()));
							value.setProvince(baseUserInfo.getProvince());
							value.setHeadImgUrl(baseUserInfo.getHeadImgUrl());
							value.setCity(baseUserInfo.getCity());
							value.setSex(baseUserInfo.getSex());
							value.setNickname(baseUserInfo.getNickname());
							value.setLanguage(baseUserInfo.getLanguage());
							
							if(wechatUserList.size() <= 0){
								wechatUserDao.insertNonEmptyWechatUser(value );
							}else{
								WechatUser wechatUser = wechatUserList.get(0);
								value.setId(wechatUser.getId());
								wechatUserDao.updateNonEmptyWechatUserById(value);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						
						logger.info(name + " 在"+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(Long.parseLong(createTime)* 1000L)) + " 关注了公众号");
					}
					
					WechatReply subscribeReply = new WechatReply();
					subscribeReply.setEventType(eventType);
					List<WechatReply> subscribeReplyList = wechatReplyDao.selectWechatReplyByObj(subscribeReply);
					if(subscribeReplyList != null && subscribeReplyList.size() > 0){
						subscribeReply = subscribeReplyList.get(0);
						// 设置回复消息的类型
						textMessage.setMsgType(subscribeReply.getMsgType());
						textMessage.setContent(subscribeReply.getContent());
						if(subscribeReply.getMsgType().equals(MessageApi.MESSAGE_TEXT)){
							message = MessageApi.textMessageToXml(textMessage);
						}
					}
					// 推送消息
					Map<String,String> textMsgMap = new HashMap<String,String>();
					textMsgMap.put("OpenId", openId);
					final String textMsg = JSON.toJSONString(textMsgMap);
					
					// 开启异步线程发送消息,等待关注消息发送给用户后再发送订单消息
					new Thread(){
						@Override
						public void run() {
							try {
								Thread.sleep(10000); // 30秒后再发送
								jmsQueueTemplate.send("orderPush",new MessageCreator() {
									
									@Override
									public Message createMessage(Session session) throws JMSException {
										
										javax.jms.TextMessage message = session.createTextMessage(textMsg);
										
										return message;
									}
						
								});
								
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
						
					}.start();
				}
				
			}
			
			return message;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
